package myJs

import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.LayerOptions
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom.{Event, _}
import org.scalajs.dom.ext.Ajax
import shared.VarTool

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.concurrent.{Future, Promise}
import scala.scalajs.js
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.Dynamic.{global=>g}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("PhoneLogin")
object PhoneLogin {

  val count = 60

  @JSExport("init")
  def init = {
    registerEvent

    bootStrapValidator

  }

  def registerEvent = {
    $(document.body).on("click", s".mySendValidCode", "", (y: Element) => {
      sendValidCode
    })
  }

  def refreshRemainTime(count: Int) = {
    Utils.mySetInterval(count, curCount => {
      $("#refreshButton").text(s"${messages("resend")}（" + curCount + "）").attr("disabled", true)
    }, () =>
      $("#refreshButton").text(messages("sendVerificationCode")).attr("disabled", false)
    )
  }

  def sendValidCode = {
    val phone = Tool.getInputByName("phone").myVal
    if (!phone.matches(VarTool.phoneRegexpStr)) {
      layer.msg(messages("pleaseEnterTheCorrectPhoneNumber"), LayerOptions.icon(5).time(3000))
      Tool.getInputByName("phone").focus()
    } else {
      refreshRemainTime(count)
      val url = g.jsRoutes.controllers.AppController.sendValidCode().url.toString
      val dict = js.Dictionary("phone" -> phone)
      val data = JSON.stringify(dict)
      Ajax.post(url = s"${url}", data = data, headers = Map("Content-Type" -> "application/json")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        val valid = rs("valid").toB
        if (!valid) {
          layer.msg(rs.myGet("message"), LayerOptions.icon(5).time(3000))
        }
      }
    }
  }

  def bootStrapValidator = {
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "phone" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "phone"->js.Dictionary(
                "country"->"CN",
                "message"->messages("illegal")
              ),
            )
          )
        } ,
        "validCode" ->{
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "blank" -> js.Dictionary()
            )
          )
        } ,
      )
    )
    $(s"#form").bootstrapValidator(dict).on("success.form.bv", (e: Event) => {
      e.preventDefault()
      val bv = $(s"#form").bv
      val url = g.jsRoutes.controllers.AppController.validCode().url.toString
      val formData = $(s"#form").serialize()
      Ajax.post(url = s"${url}", data = formData, headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).
        map { xhr =>
          val rs = xhr.responseText.toJDJAn
          val valid = rs("valid").toB
          if (valid) {
            bv.defaultSubmit()
          } else {
            bv.updateMessage("validCode", "blank", messages("ErrorInVerificationCode"))
            bv.updateStatus("validCode", "INVALID", "blank")
          }
        }
    })
  }


}
